package com.example.questionbase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.questionbase.pojo.User;
import com.example.questionbase.pojo.dto.UserDto;
import com.example.questionbase.service.UserService;
import com.example.questionbase.mapper.UserMapper;
import com.example.questionbase.util.Constants;
import com.example.questionbase.util.Result;
import com.example.questionbase.util.UserJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
* @author fan
* @description 针对表【user(用户信息表)】的数据库操作Service实现
* @createDate 2024-03-21 21:18:50
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @Override
    public Result login(User user) {

        //账户密码
        String account = user.getAccount();
        String password = user.getPassword();

        //账户为空
        if (!StringUtils.isBlank(account) && !StringUtils.isBlank(password)) {
            user = this.getOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
            if (user == null) {
                return Result.buildResult(Constants.ResponseCode.DATA_NOT_EXIST, "用户不存在");
            }
            //1.2对比密码
            String salt = user.getSalt();
            String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());

            if (!pswd.equals(user.getPassword())) {
                return Result.buildErrorResult(Constants.ResponseCode.LOGIN_PASSWORD_ERROR.getInfo());
            }
            //1.3 返回数据 jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", UserJwtUtil.getToken((long) user.getId()));
            user.setPassword("");
            user.setSalt("");
            map.put("user", user);
            return Result.buildSuccessResultWithData(map);
        }
        return Result.buildResult(Constants.ResponseCode.DATA_NOT_EXIST, "账户为空或密码为空");
    }

    /**
     * 用户添加
     *
     * @param user
     * @return
     */
    @Override
    public Result add(User user) {

        //用户数据
        String name = user.getName();
        String account = user.getAccount();
        String password = user.getPassword();

        //用户名，密码，账户是否为空
        if (!StringUtils.isBlank(name) && !StringUtils.isBlank(account) && !StringUtils.isBlank(password)) {
            User one = this.getOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
            //账户存在
            if (one != null) {
                return Result.buildResult(Constants.ResponseCode.DATA_EXIST, "账户已经存在！");
            }
            //生成salt
            String salt = UserJwtUtil.generalKey().getEncoded().toString();
            String passwordPro = DigestUtils.md5DigestAsHex((password + salt).getBytes());

            //设置加密密码
            user.setSalt(salt);
            user.setPassword(passwordPro);

            boolean save = this.save(user);

            if (save) {
                return Result.buildSuccessResult();
            } else {
                return Result.buildErrorResult();
            }
        }
        return Result.buildResult(Constants.ResponseCode.DATA_NOT_EXIST, "添加用户的信息不全！");
    }

    /**
     * 用户删除
     *
     * @param user
     * @return
     */
    @Override
    public Result delete(User user) {

        //校验参数
        if (user == null) return Result.buildErrorResult("参数为空");

        Integer id = user.getId();

        if (id.equals(0)) return Result.buildErrorResult("id为空");


        User one = this.getById(id);

        if (one == null) {
            Result.buildErrorResult("id错误");
        }

        one.setRole(Constants.Delete);

        boolean update = this.updateById(one);

        if (update) {
            return Result.buildSuccessResult();
        } else {
            return Result.buildErrorResult();
        }
    }

    /**
     * 用户修改
     *
     * @param user
     * @return
     */
    @Override
    public Result update(UserDto user) {

        if (StringUtils.isBlank(user.getId() + "")) {
            return Result.buildResult(Constants.ResponseCode.DATA_NOT_EXIST, "id不存在！");
        }

        String account = user.getAccount();
        String password = user.getPassword();
        String newPassword = user.getNewPassword();
        //账户不为空，
        if (!StringUtils.isBlank(account) && !StringUtils.isBlank(password) && !StringUtils.isBlank(newPassword)) {
            User one = this.getOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
            if (one == null) {
                return Result.buildResult(Constants.ResponseCode.DATA_NOT_EXIST, "用户不存在");
            }
            //1.2对比密码
            String salt = one.getSalt();
            String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());

            //判断原密码是否正确
            if (!pswd.equals(one.getPassword())) {
                return Result.buildResult(Constants.ResponseCode.UPDATE_FAIL, "原密码错误");
            }

            salt = UserJwtUtil.generalKey().getEncoded().toString();

            user.setSalt(salt);
            user.setPassword(DigestUtils.md5DigestAsHex((newPassword + salt).getBytes()));

            User save = new User();

            BeanUtils.copyProperties(user, save);

            boolean update = this.updateById(save);
            if (update) {
                return Result.buildSuccessResult();
            } else {
                return Result.buildErrorResult();
            }
        }
        return Result.buildResult(Constants.ResponseCode.DATA_NOT_EXIST, "账户为空或密码为空");


    }

    /**
     * 分页查询用户
     * @param current
     * @param size
     * @param name
     * @return
     */
    public Result page(int current, int size , String name){

        if (current==0){
            current = Constants.CURRENTPAGE;
        }

        if (size==0){
            size = Constants.SIZE;
        }

        if (name==null) {
            name =  new String();
        }


        Page<User> pageObject = new Page<>(current, size);
        Page<User> page = this.page(pageObject, new LambdaQueryWrapper<User>().ne(User::getRole,Constants.Delete).like(User::getName,name));
        return Result.buildSuccessResultWithData(page);
    }

}




